package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    //serverSocket 就是外场拉客的小哥
    //clientSocket 就是内场服务的小姐姐
    //serverSocket 只有一个，clientSocket 会给每个客户端都分配一个
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            Socket clientSocket = serverSocket.accept();
            //如果直接调用，该方法会影响这个循环的二次执行，导致 accept 不及时了
            //创建新线程，用新线程来调用 processConnection
            //每次来一个新的客户端都创建一个新的线程
            //clientSocket是服务器的Socket 通过这个Socket和客户端进行通信
            Thread t = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();

        }
    }

    //通过这个方法来处理一个连接
    //读取请求
    //根据请求计算响应
    //把响应返回给客户端
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            //输入 从网卡读 输出 往网卡写
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);//相当于字符流
            PrintWriter printWriter = new PrintWriter(outputStream);//OutputStream字节流 PrintWriter字符流
            while(true){
                //1.读取请求
                if(!scanner.hasNext()){
                    //读取的流到了结尾了（对端关闭了）
                    System.out.printf("[%s:%d] 客户端下线\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //直接使用 scanner 读取一段字符串
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应写回给客户端 响应里也是要带上换行的
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req: %s;resp: %s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }

    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
